﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Timers;
using DataAccessObject;
using EntityObject;
using ThangNM_LIB.FUNC;
using System.Threading.Tasks;
using Facebook;

namespace ThangNM_WinSV
{
    partial class Facebook_Request : ServiceBase
    {
        public static Int16 iThread_Count;

        Timer timerFacebookRequestApi;
        Timer timerAppSendResult;

        public Facebook_Request()
        {
            System.Diagnostics.Debugger.Launch();
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            try
            {
                iThread_Count = 0;

                timerFacebookRequestApi = new Timer();
                timerFacebookRequestApi.Interval = Properties.Settings.Default.IntervalAutoReport * 1000;
                timerFacebookRequestApi.Elapsed += this.evttimerAutoScan;
                timerFacebookRequestApi.Start();

                //timerAppSendResult = new Timer();
                //timerAppSendResult.Interval = Properties.Settings.Default.IntervalAutoReport * 1000;
                //timerAppSendResult.Elapsed += this.evttimerAutoScan;
                //timerAppSendResult.Start();
            }
            catch (Exception ex)
            {
                ErrorLog.WriteToEventLog(String.Format("Err:{0} - Trace: {1}", ex.ToString(), ex.StackTrace), Properties.Settings.Default.Service_Name, EventLogEntryType.Error);
            }
        }

        public void evttimerAutoScan(object sender, System.Timers.ElapsedEventArgs args)
        {
            Timer timer = (Timer)sender;
            try
            {
                timer.Stop();
                Int16 iTop_Limit = Convert.ToInt16(Properties.Settings.Default.Top_Limit - iThread_Count);
                DataTable dt = (new RequestDAO()).SelectBy_iStatus(FacebookApp.SharedLibraries.Constants.Request_iStatus.received, FacebookApp.SharedLibraries.Constants.Request_iStatus.processing, iTop_Limit);
                if (CommonsCheck.DataTable_OK(dt))
                {
                    List<RequestEO> lstRes = new List<RequestEO>();
                    lstRes = (List<RequestEO>)ConvertEx.ConvertDataTableToListObject<RequestEO>(dt, lstRes.GetType());
                    if (CommonsCheck.ListObject_OK(lstRes))
                    {
                        if (iThread_Count < Properties.Settings.Default.Top_Limit)
                        {
                            iThread_Count = Convert.ToInt16(iThread_Count + lstRes.Count);
                            Parallel.ForEach(lstRes, (item) => { Thread_Request_Api(item); });
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ErrorLog.WriteToEventLog(string.Format("Err:{0} - Trace: {1}", ex.ToString(), ex.StackTrace), Properties.Settings.Default.Service_Name, EventLogEntryType.Error);
            }
            finally
            {
                timer.Start();
            }
        }

        public void Thread_Request_Api(RequestEO objInput)
        {
            Boolean isSuccess = false;
            try
            {
                objInput.sFID = StringEx.Trim(objInput.sFID);

                FacebookClient FBClient = new FacebookClient();
                FBClient.AppId = OtherEx.getAppSettings("AppId");
                FBClient.AppSecret = OtherEx.getAppSettings("AppSecret");
                FBClient.AccessToken = "CAACEdEose0cBACwHWcP5MEflY1FQpZCFuKotcMZC7WzXZANUZAVpq0JeDWHR96MRPRddAm0EamkY9bwwfB89POtOvHYxs9y3xeLDM5G2rJkhTSWlFlAzOQz4V4cW5oO4GAyZBxoKd9SZB1Jkv0iaNWdaZAN10oJZBEVtscX4sM8HhQNKoGL4tJikxhEBnnymhyW9aDCYLH8cCtlZCcMwgMZAha72kaXYQ3HZBIZD";
                FacebookApp.SharedLibraries.ScheduleJobs ctl = new FacebookApp.SharedLibraries.ScheduleJobs();
                Boolean isSQLite = false;
                switch (objInput.iType)
                {
                    case FacebookApp.SharedLibraries.Constants.Request_iType.user:
                        isSuccess = ctl.getFacebook_Current_User(FBClient, new FBEO(), isSQLite);
                        break;
                    case FacebookApp.SharedLibraries.Constants.Request_iType.page:
                        isSuccess = ctl.getFacebook_Page(FBClient, new FBEO(), Convert.ToInt64(objInput.sFID), true, isSQLite);
                        break;
                    case FacebookApp.SharedLibraries.Constants.Request_iType.group:
                        isSuccess = false;
                        break;
                    case FacebookApp.SharedLibraries.Constants.Request_iType.feed:
                        isSuccess = ctl.getFacebook_Feed(FBClient, new FBEO(), Convert.ToInt64(objInput.sFID), objInput.bLike, objInput.bComment, objInput.bReply, objInput.bEmail, isSQLite);
                        break;
                    case FacebookApp.SharedLibraries.Constants.Request_iType.post:
                        isSuccess = ctl.getFacebook_Post(FBClient, new FBEO(), 0, objInput.sFID, objInput.bLike, objInput.bComment, objInput.bReply, objInput.bEmail, isSQLite);
                        break;
                    case FacebookApp.SharedLibraries.Constants.Request_iType.photo:
                        isSuccess = false;
                        break;
                    case FacebookApp.SharedLibraries.Constants.Request_iType.video:
                        isSuccess = false;
                        break;
                    case FacebookApp.SharedLibraries.Constants.Request_iType.fb_event:
                        isSuccess = false;
                        break;
                    case FacebookApp.SharedLibraries.Constants.Request_iType.like:
                        isSuccess = ctl.getFacebook_Like(FBClient, new FBEO(), 0, objInput.sFID, isSQLite);
                        break;
                    case FacebookApp.SharedLibraries.Constants.Request_iType.comment:
                        isSuccess = ctl.getFacebook_Comment(FBClient, new FBEO(), 0, objInput.sFID, objInput.bReply, objInput.bEmail, isSQLite);
                        break;
                    case FacebookApp.SharedLibraries.Constants.Request_iType.reply:
                        isSuccess = ctl.getFacebook_Reply(FBClient, new FBEO(), 0, objInput.sFID, 0, objInput.bEmail, isSQLite);
                        break;
                    default:
                        isSuccess = false;
                        break;
                }
            }
            catch (Exception ex)
            {
                ErrorLog.WriteToEventLog(string.Format("Err:{0} - Trace: {1}", ex.ToString(), ex.StackTrace), Properties.Settings.Default.Service_Name, EventLogEntryType.Error);
                isSuccess = false;
            }
            iThread_Count--;
            try
            {
                objInput.iStatus = (isSuccess ? FacebookApp.SharedLibraries.Constants.Request_iStatus.success : FacebookApp.SharedLibraries.Constants.Request_iStatus.error);
                (new RequestDAO()).Insert_Update_Delete(objInput, ConstEx.Insert_Update_Delete.Update);
            }
            catch (Exception ex)
            {
                ErrorLog.WriteToEventLog(string.Format("Err:{0} - Trace: {1}", ex.ToString(), ex.StackTrace), Properties.Settings.Default.Service_Name, EventLogEntryType.Error);
            }
        }

        protected override void OnStop()
        {
            try
            {
                timerFacebookRequestApi.Stop();
            }
            catch (Exception ex)
            {
                ErrorLog.WriteToEventLog(string.Format("Err:{0} - Trace: {1}", ex.ToString(), ex.StackTrace), Properties.Settings.Default.Service_Name, EventLogEntryType.Error);
            }
        }
    }
}
